package controller

import (
	"ginfast/api/system/dto"
	"ginfast/api/system/model"
	"ginfast/pkg/ctx"
	"ginfast/pkg/orm"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// Dict 系统管理字典
type Dict struct {
}

// ListHandler 字典列表
func (Dict) ListHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	var data []model.DictData
	total, _ := p.DbModelWhere(&model.DictData{}).Find(&data)
	ctx.JSONWriteTotal(total, data, c)
}

// ListExcludeHandler 字典列表（排除节点）
func (Dict) ListExcludeHandler(c *gin.Context) {
	// id, err := ctxQueryInt(c, "id")
	// if err != nil {
	// 	JSONP(StatusError).WriteTo(c)
	// }
	// where := fmt.Sprintf("id != %d", id)
	// var depts []model.Dept
	// orm.DbFindAll(where, depts, "order_num asc")
	ctx.JSONWriteData(nil, c)
}

// GetHandler 查询字典详细
func (Dict) GetHandler(c *gin.Context) {
	util.QueryByID(&model.DictData{}, c)
}

// DictTypeHandler 根据字典类型查询字典数据信息
func (Dict) DictTypeHandler(c *gin.Context) {
	dtype := c.Query("dictType")
	var data []model.DictData
	if _, err := orm.DbFindBy(&data, "Type = ?", dtype); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(data, c)
}

// RoleDeptTreeselectHandler 根据角色ID查询字典树结构
func (Dict) RoleDeptTreeselectHandler(c *gin.Context) {
	ctx.JSONWriteData(nil, c)
}

// AddHandler 新增字典
func (Dict) AddHandler(c *gin.Context) {
	var p model.DictData
	//获取参数
	if err := c.ShouldBind(&p.DictDataOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbCreate(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateHandler 修改字典
func (Dict) UpdateHandler(c *gin.Context) {
	var p model.DictData
	//获取参数
	if err := c.ShouldBind(&p.DictDataOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateModel(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 删除字典
func (Dict) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.DictData{}, c)
}

func (o Dict) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/:id", o.GetHandler)
	r.GET("/type", o.DictTypeHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.DELETE("/:id", o.DeleteHandler)
}
